using System.Reflection;
using System.Runtime.Loader;
using Microsoft.Extensions.DependencyModel;

namespace ZeroSum.Helpers;

/// <summary>
///     Assembly辅助工具类
/// </summary>
public static class AssemblyHelper
{
    /// <summary>
    ///     获取运行时所有项目类型的程序集
    /// </summary>
    /// <returns></returns>
    public static IEnumerable<Assembly> GetProjectAssemblies()
    {
        var assemblies = DependencyContext.Default.RuntimeLibraries;
        return assemblies
            .Where(x => x.Type == "project")
            .Select(x => AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(x.Name)));
    }

    /// <summary>
    ///     获取运行时所有指定前缀的包类型的程序集
    /// </summary>
    /// <param name="prefix"></param>
    /// <returns></returns>
    public static IEnumerable<Assembly> GetPackageAssemblies(string prefix)
    {
        var assemblies = DependencyContext.Default.RuntimeLibraries;
        return assemblies
            .Where(x => x.Type == "package" && x.Name.StartsWith(prefix))
            .Select(x => AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(x.Name)));
    }
}